<template>
  <div class="user-setting-bg">
    <button class="back-btn" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      <span>返回</span>
    </button>
    <div class="user-setting-root">
      <h2 class="title">用户插件设置</h2>
      <div class="setting-list">
        <div class="setting-item" v-for="item in pluginList" :key="item.plugin_name">
          <span class="setting-label">{{ item.label }}</span>
          <el-switch
            v-model="item.enabled"
            active-text="开"
            inactive-text="关"
            @change="onSwitchChange(item)"
          />
          <span class="setting-status">{{ item.enabled ? '开' : '关' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getAIListAPI, updateAIStatusAPI } from '@/api/aiAPI'
import { ArrowLeft } from '@element-plus/icons-vue'
const router = useRouter()
const goBack = () => router.back()

interface PluginItem {
  plugin_name: string
  label: string
  enabled: boolean
}

const pluginList = ref<PluginItem[]>([
  { plugin_name: 'priority_plugin', label: '优先级插件', enabled: false },
  { plugin_name: 'security_plugin', label: '安全插件', enabled: false },
  { plugin_name: 'spam_plugin', label: '反垃圾插件', enabled: false },
])

const fetchStatus = async () => {
  const res = await getAIListAPI()
  if (res.code === 200) {
    for (const item of pluginList.value) {
      const found = res.data.find((ai) => ai.name === item.plugin_name)
      if (found) item.enabled = found.enabled
    }
  }
}

const onSwitchChange = async (item: PluginItem) => {
  try {
    await updateAIStatusAPI({
      plugin_name: item.plugin_name,
      is_enabled: item.enabled,
    })
  } catch (error) {
    console.log('Error updating AI status:', error)
  }

  // fetchStatus()
}

onMounted(fetchStatus)
</script>

<style scoped>
.user-setting-bg {
  min-height: 100vh;
  background: #ffffff;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
.back-btn {
  position: absolute;
  top: 40px;
  left: 60px;
  background: none;
  border: none;
  color: #685f5f;
  font-size: 20px;
  cursor: pointer;
  font-weight: bold;
  z-index: 2;
}
.back-btn:hover {
  color: #d16262;
}

.user-setting-root {
  width: 480px;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 3px 16px rgba(0, 0, 0, 0.1);
  padding: 48px 56px 40px 56px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  font-size: 26px;
  color: #d16262;
  margin-bottom: 40px;
  text-align: center;
}
.setting-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 36px;
}
.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.setting-label {
  font-size: 18px;
  color: #333;
}
.setting-status {
  margin-left: 16px;
  font-size: 16px;
  color: #d16262;
  min-width: 24px;
  text-align: center;
}
</style>
